package com.tbs.parkingsaleapp.UI.HomePage;

import abstergo.tbs.betterasyc.Handler.HandlerMananger;
import abstergo.tbs.betterasyc.Handler.IHandlerAction;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.tbs.parkingsaleapp.Http.JsonData.LocationInfo;
import com.tbs.parkingsaleapp.SystemManager.Handler.CallBacks.ParkDataUpdater;
import com.tbs.parkingsaleapp.SystemManager.Handler.HandlerConst;
import com.tbs.parkingsaleapp.SystemManager.SystemDataMananger;
import com.tbs.parkingsaleapp.UI.Adapters.InfoWindowAdapter;
import com.tbs.parkingsaleapp.UI.Listenners.InfoWindowClicker;
import com.tbs.parkingsaleapp.R;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.*;
import com.tencent.tencentmap.mapsdk.maps.model.*;

public class HomeFragment extends Fragment  implements TencentLocationListener, LocationSource {

    public static final String MARKERUPDATE="U_MARKER";
    public PopupWindow window;
    public  Marker PutMarker(double lat,double lng)
    {
        LatLng pos=new LatLng(lat,lng);
        return mTencentMap.addMarker(new MarkerOptions(pos));
    }
    ListView ls;
    TextView com,loc;

    public void Show(LocationInfo info)
    {
        com.setText(info.getCompany().get(0).toString());
        loc.setText(info.getLocation().toString());
        ls.setAdapter(new InfoWindowAdapter(this,info.getLocation().getId()));
        window.showAsDropDown(getView());
    }

    private TencentLocationManager mLocationManager;
    private static TencentMap mTencentMap;
    private TencentLocationRequest mRequest;
    private OnLocationChangedListener mLocationChangedListener;
    TextureMapView mapView;
    View root;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        root=inflater.inflate(R.layout.fragment_home,container,false);
        mLocationManager=TencentLocationManager.getInstance(getContext());
        if(!HandlerMananger.Instance().HasSubscribe(HandlerConst.DATA_FILLED))
        {
            HandlerMananger.Subscribe(HandlerConst.DATA_FILLED, new IHandlerAction() {
                @Override
                public void Handle(Message rawmsg) {
                    for (LocationInfo ix:SystemDataMananger.AllLocations()
                    ) {
                        Marker marker= PutMarker(ix.getLocation().getLatitude(),ix.getLocation().getLongitude());
                        marker.setInfoWindowEnable(true);
                        MarkerClickData clickData=new MarkerClickData(ix.getLocation().getId());
                        String text="";
                        if(ParkDataUpdater.Instance().getUpdatedResult(ix.getLocation().getId())==ParkDataUpdater.UPDATING)
                        {
                            clickData.setClickable(false);
                            text="读取中...";
                        }
                        else
                        {
                            clickData.setClickable(true);
                            text=String.format("车位数：%d",ix.getParkNumber());
                        }
                        marker.setTag(clickData);
                        marker.setSnippet(String.format(text,ix.getParkNumber()));
                        marker.setTitle(ix.getLocation().getName());
                        SystemDataMananger.markers.put(ix.getLocation().getId(),marker);
                        marker.showInfoWindow();

                    }
                }
            },false);
        }
        ParkDataUpdater.Instance().setUpdateder(MARKERUPDATE, new ParkDataUpdater.IOnParkDataUpdated() {
            @Override
            public void action(int location) {
               Marker marker= SystemDataMananger.markers.get(location);
               LocationInfo info=SystemDataMananger.FindLocation(location);
                marker.hideInfoWindow();
                MarkerClickData clickData= (MarkerClickData) marker.getTag();
                clickData.setClickable(true);
                marker.setSnippet(String.format("车位数：%d",info.getParkNumber()));
                marker.showInfoWindow();

            }
        });
        window=new PopupWindow(InitMainPopWindow(),ViewGroup.LayoutParams.MATCH_PARENT,1600);
        window.setOutsideTouchable(true);
        mapView=root.findViewById(R.id.map);
        mTencentMap= mapView.getMap();
        mTencentMap.setOnMapLongClickListener(new TencentMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                Toast.makeText(HomeFragment.this.getContext(),"正在更新数据",Toast.LENGTH_SHORT).show();
                LocationInfoUpdates(true);
            }
        });

        mTencentMap.setOnMapLoadedCallback(new TencentMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {

                mTencentMap.setLocationSource(HomeFragment.this);
        //设置当前位置可见
        mTencentMap.setMyLocationEnabled(true);
        mLocationManager.requestSingleFreshLocation(null, HomeFragment.this, Looper.getMainLooper());
            }
        });
        InfoWindowClicker clicker= new InfoWindowClicker(this);
        mTencentMap.setOnInfoWindowClickListener(clicker);
        if(SystemDataMananger.isFirst())
        LocationInfoUpdates(true);
        else
            callMapUpdate();
        return root;
    }

    public static void callMapUpdate()
    {
        Message message=new Message();
        message.what=HandlerConst.DATA_FILLED;
        HandlerMananger.Instance().SendMsg(message);
    }

    void LocationInfoUpdates(boolean force)
    {
        SystemDataMananger.FillData(getContext(),force);
    }
    @Override
    public void onStart() {
        super.onStart();
        mapView.onStart();

    }
    View InitMainPopWindow()
    {
        View root=LayoutInflater.from(getContext()).inflate(R.layout.poplayout,null);
        ls=root.findViewById(R.id.pop_list);
        ls.setDivider(getResources().getDrawable(R.drawable.blank));
        ls.setDividerHeight(38);
        com=root.findViewById(R.id.pop_company);
        loc=root.findViewById(R.id.pop_location);
        TextView t=root.findViewById(R.id.handle_pop);
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mLocationChangedListener= onLocationChangedListener;
        //mLocationManager=TencentLocationManager.getInstance(getContext());

    }

    @Override
    public void deactivate() {
//        mLocationManager.removeUpdates(this);
//        mLocationManager = null;
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        if (i == TencentLocation.ERROR_OK && mLocationChangedListener != null) {
            Location location = new Location(tencentLocation.getProvider());
            //设置经纬度
            location.setLatitude(tencentLocation.getLatitude());
            location.setLongitude(tencentLocation.getLongitude());
            //设置精度，这个值会被设置为定位点上表示精度的圆形半径
            location.setAccuracy(tencentLocation.getAccuracy());
            //设置定位标的旋转角度，注意 tencentLocation.getBearing() 只有在 gps 时才有可能获取
            location.setBearing(tencentLocation.getBearing());


            //将位置信息返回给地图
            mLocationChangedListener.onLocationChanged(location);
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }
}